<template>
  <a-layout>
    <a-layout-sider
      breakpoint="lg"
      collapsed-width="0"
      @collapse="onCollapse"
      @breakpoint="onBreakpoint"
    >
      <a-menu
        theme="dark"
        v-model:selectedKeys="current"
        mode="inline"
        @select="selectMenu"
      >
        <a-sub-menu v-for="menu in menus" :key="menu.id">
          <template #title>
            <span class="submenu-title-wrapper">{{ menu.name }}</span>
          </template>
          <a-menu-item v-for="child in menu.children" :key="child.url">{{
            child.name
          }}</a-menu-item>
        </a-sub-menu>
      </a-menu>
    </a-layout-sider>
    <a-layout>
      <a-layout-header :style="{ background: '#fff', padding: 0 }">
        <div>
          <img
            style="height: 60px; vertical-align: middle"
            src="@/views/home/logo.png"
          />
        </div>
        <a-menu
          mode="horizontal"
          style="margin-right: 10px; float: right; margin: -60px 20px 10px 10px"
          @select="selectCurrUser"
        >
          <a-sub-menu>
            <template #title>
              <a-avatar
                v-if="currImageUrl"
                @click="setAvatar"
                :src="currImageUrl"
                style="vertical-align: middle"
              />
              <span
                v-else
                @click="setAvatar"
                style="
                  vertical-align: middle;
                  font-size: 14px;
                  color: #aa0000;
                  cursor: pointer;
                "
                >设置头像</span
              >
              <span>&nbsp;&nbsp;</span>
              <span style="vertical-align: middle"
                >{{ currUser.userId }}【{{ currUser.userName }}】</span
              >
            </template>
            <a-menu-item @click="openUpda" key="people">个人信息</a-menu-item>
            <a-menu-item @click="openUpdb" key="password">密码修改</a-menu-item>
            <a-menu-item key="exit">退出系统</a-menu-item>
          </a-sub-menu>
        </a-menu>
      </a-layout-header>
      <a-layout-content :style="{ margin: '24px 16px 0' }">
        <div
          :style="{ padding: '24px', background: '#fff', minHeight: '580px' }"
        >
          <router-view></router-view>
        </div>
      </a-layout-content>
      <a-layout-footer style="text-align: center">
        supermarket-management-system ©2021 Created by group nine
      </a-layout-footer>
    </a-layout>
  </a-layout>

  <!-- 设置头像弹框 -->
  <a-modal v-model:visible="visible" title="设置头像" @ok="execUpload">
    <a-upload
      list-type="picture-card"
      class="avatar-uploader"
      :show-upload-list="false"
      :before-upload="() => false"
      @change="handleChange"
    >
      <img v-if="imageUrl" :src="imageUrl" />
      <div v-else>
        <plus-outlined />
        <div class="ant-upload-text">选择头像</div>
      </div>
    </a-upload>
  </a-modal>

  <!-- 个人信息弹窗 -->
  <a-modal v-model:visible="visible2" title="个人信息修改" @ok="inforUpd">
    <a-form
      :model="updObja"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 14 }"
    >
      <a-form-item label="编号">
        <a-input v-model:value="updObja.st_id" disabled />
      </a-form-item>

      <a-form-item label="姓名">
        <a-input v-model:value="updObja.st_name" />
      </a-form-item>

      <a-form-item label="电话">
        <a-input v-model:value="updObja.st_tel" />
      </a-form-item>

      <a-form-item label="性别">
        <a-input v-model:value="updObja.st_sex" />
      </a-form-item>

      <a-form-item :wrapper-col="{ span: 14, offset: 4 }"> </a-form-item>
    </a-form>
  </a-modal>

  <!-- 修改密码弹窗 -->
  <a-modal v-model:visible="visible3" title="修改密码" @ok="pwdUpd">
    <a-form
      :model="updObjb"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 14 }"
      :rules="rules"
      ref="checkPwd"
    >
      <a-form-item label="请输入旧密码" name="old">
        <a-input v-model:value="updObjb.old" />
      </a-form-item>
      <a-form-item label="请输入新密码" name="st_pwd">
        <a-input v-model:value="updObjb.st_pwd" />
      </a-form-item>
      <a-form-item label="确认新密码" name="st_pwd1">
        <a-input v-model:value="updObjb.st_pwd1" />
      </a-form-item>

      <a-form-item :wrapper-col="{ span: 14, offset: 4 }"> </a-form-item>
    </a-form>
  </a-modal>
</template>








<script setup>
import { ref, reactive, computed } from "vue";
import { useRouter } from "vue-router";
import { get, del, post, getBlob, tip, removeLocalToken, put } from "@/common";
let checkold = async (rule, value) => {
  if (!value) {
    return Promise.reject("请输入旧密码");
  } else if (value != currUser.value.userPwd) {
    return Promise.reject("旧密码错误");
  }
};
let checknew = async (rule, value) => {
  if (!value) {
    return Promise.reject("请确定新密码");
  } else if (value != updObjb.st_pwd) {
    return Promise.reject("新密码错误");
  }
};
const checkPwd=ref();
const rules = {
  old: [
    {
      validator: checkold,
      trigger: "blur",
    },
  ],
  st_pwd: [
    {
      required: true,
      message: "请输入新密码",
      trigger: "blur",
    },
  ],
  st_pwd1: [
    {
      validator: checknew,
      trigger: "blur",
    },
  ],
};

const columns = [
  {
    dataIndex: "st_id", //服务端数据
  },
  {
    dataIndex: "st_name",
  },
  {
    dataIndex: "st_tel",
  },
  {
    dataIndex: "st_sex",
  },
  {
    dataIndex: "st_pwd",
  },
];

const router = useRouter();

const selectMenu = ({ item, key, selectkeys }) => {
  console.log(item, key, selectkeys);
  router.push({ path: key });
};

const current = ref(["mail"]);

const menus = ref([]);

const getMenus = () => {
  get("/security/home/menus").then((res) => {
    menus.value = res.data;
  });
};

getMenus();

const onCollapse = (collapsed, type) => {
  console.log(collapsed, type);
};

const onBreakpoint = (broken) => {
  console.log(broken);
};

//当前用户信息
const currUser = ref({});
const getCurrUser = () => {
  get("/security/home/curr-user", {}, { loading: false }).then((res) => {
    currUser.value = res.data;
    getAvatar();
  });
};

getCurrUser();

const currImageUrl = ref("");
const getAvatar = () => {
  if (!currUser.value || !currUser.value.avatar) {
    return;
  }
  getBlob(
    "/security/home/avatar/" + currUser.value.avatar,
    {},
    { loading: false }
  ).then((blob) => {
    const reader = new FileReader();
    reader.addEventListener("load", () => {
      currImageUrl.value = reader.result;
    });
    reader.readAsDataURL(blob);
  });
};

const selectCurrUser = ({ item, key, selectedKeys }) => {
  switch (key) {
    case "exit": //退出系统
      del("/security/home/exit").then((res) => {
        tip.success("您已成功退出系统，请重新登录！");
        removeLocalToken();
        router.push({ path: "/login" });
      });
      break;
  }
};

//分页处理-start
const query = reactive({
  st_id: "",
  st_name: "",
  st_tel: "",
  st_sex: "",
  st_pwd: "",
}); //定义查询参数

const page = ref({}); //接收服务端返回的分页对象

//分页引擎
const pagination = reactive({
  current: 1, //当前页
  pageSize: 5, //每页记录数
  total: 0, //总记录数
  pageSizeOptions: ["5", "10", "20", "30", "100"], //每页记录下拉框的选型
  showSizeChanger: true, //是否展示每页记录数下拉框
  showQuickJumper: true, //是否展示快速跳转
  showTotal: (total, range) => {
    //展示总页数等文字说明信息的
    return (
      "共" +
      total +
      "条记录,当前第" +
      pagination.current +
      "页" +
      (range[1] - range[0] + 1) +
      "条记录"
    );
  },
});

//获取当前分页
const getPage = (pageNum = 1) => {
  query.pageNum = pageNum;
  query.pageSize = pagination.pageSize;

  get("/security/home", query).then((res) => {
    page.value = res.data; //将服务端传来的分页数据赋值予page

    //更新分页引擎
    pagination.current = page.value.current;
    pagination.pageSize = page.value.pageSize;
    pagination.total = page.value.total;
  });
};
getPage(1); //页面加载是，首先加载第一页

//当分页发送变化时（如：页码、每页记录数变化时）
const handleTableChange = (pagi, filters, sorter, { currentDataSource }) => {
  pagination.current = pagi.current;
  pagination.pageSize = pagi.pageSize;
  pagination.total = pagi.total;

  getPage(pagination.current);
};

//分页处理-end

//头像上传
import { PlusOutlined } from "@ant-design/icons-vue";

const avatarFile = ref(null);
const imageUrl = ref("");
const visible = ref(false);

const setAvatar = () => {
  visible.value = true;
};

//选择头像
const handleChange = (info) => {
  avatarFile.value = info.file;
  const reader = new FileReader();
  reader.addEventListener("load", () => {
    imageUrl.value = reader.result;
  });
  reader.readAsDataURL(info.file);
};

//执行上传
const execUpload = () => {
  if (!avatarFile.value) {
    tip.error("请选择头像！");
    return;
  }
  const formData = new FormData();
  formData.append("avatar", avatarFile.value);
  post("/security/home/avatar", formData).then((res) => {
    tip.success("头像设置成功！");
    visible.value = false;
    getCurrUser();
  });
};

//修改
const updObja = reactive({
  st_id: "",
  st_name: "",
  st_tel: "",
  st_sex: "",
});
const visible2 = ref(false);
//打开窗口
const openUpda = () => {
  updObja.st_id = currUser.value.userId;
  updObja.st_name = currUser.value.userName;
  updObja.st_tel = currUser.value.userTel;
  updObja.st_sex = currUser.value.userSex;

  visible2.value = true;
};
//执行修改
const inforUpd = () => {
  put("/security/home", updObja).then((res) => {
    updObja.st_id = ""; //清空窗口数据
    updObja.st_name = ""; //清空窗口数据
    updObja.st_tel = ""; //清空窗口数据
    updObja.st_sex = ""; //清空窗口数据

    visible2.value = false;
    tip.success("修改记录成功！");
    location.reload();
  });
};

//修改
const updObjb = reactive({
  st_id: "",
  old: "",
  st_pwd1: "",
  st_pwd: "",
});
const visible3 = ref(false);
//打开窗口
const openUpdb = () => {
  updObjb.st_id = currUser.value.userId;

  visible3.value = true;
};
//执行修改
const pwdUpd = () => {
  put("/security/home", updObjb).then((res) => {
    updObjb.st_id = ""; //清空窗口数据
    updObjb.st_pwd = ""; //清空窗口数据

    visible3.value = false;
    tip.success("修改密码成功！");
    getPage(page.current);
  });
};
</script>
<style>
#components-layout-demo-responsive .logo {
  height: 32px;
  background: rgba(255, 255, 255, 0.2);
  margin: 16px;
}

.site-layout-sub-header-background {
  background: #fff;
}

.site-layout-background {
  background: #fff;
}

[data-theme="dark"] .site-layout-sub-header-background {
  background: #141414;
}

/* 上传头像样式 */
.avatar-uploader {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
}
.avatar-uploader > .ant-upload {
  width: 300px;
  height: 300px;
}
.avatar-uploader img {
  max-width: 300px;
  max-height: 300px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>